#pragma once
#include "Protocol.hpp"

enum
{
    Success = 0,
    Div_Zero,
    Mod_Zero,
    Other_Oper
};

class ServerCal
{
public:
    ServerCal()
    {
    }
    ~ServerCal()
    {
    }
    response Calculatorhelper(const request &req)
    {
        response resp;
        switch (req.oper)
        {
        case '+':
            resp.result = req.x + req.y;
            resp.code = Success;
            break;
        case '-':
            resp.result = req.x - req.y;
            resp.code = Success;
            break;
        case '*':
            resp.result = req.x * req.y;
            resp.code = Success;
            break;
        case '/':
        {
            if (req.y == 0)
                resp.code = Div_Zero;
            else
            {
                resp.result = req.x / req.y;
                resp.code = Success;
            }
        }
        break;
        case '%':
        {
            if (req.y == 0)
                resp.code = Mod_Zero;
            else
            {
                resp.result = req.x % req.y;
                resp.code = Success;
            }
        }
        break;
        default:
            resp.result = ' ';
            resp.code = Other_Oper;
            break;
        }
        return resp;
    }

    std::string Calculator(std::string &package)
    {
        std::string content;
        // 当解析的时候发现不符合协议就会返回false
        bool r = decode(package, &content);
        if (r == false)
        {
            lg(DEBUG, "server decode failed");
            return "";
        }
        request req;
        r = req.Deserialize(content);
        if (r == false)
        {
            lg(DEBUG, "server Deserialize failed");
            return "";
        }

        response resp;
        resp = Calculatorhelper(req);
        std::string p = "";
        resp.Serialize(&p);
        p = encode(p);
        if (p.empty())
        {
            lg(DEBUG, "");
        }
        return p;
    }
};
